package com.zhuimeng.minicat.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class BootStrap {
    private int port=8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void start() throws Exception{
        loadServlet();
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();;

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while (true){
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    private Mapper mapper = new Mapper();
    private void loadServlet(){
        InputStream resourceAsStream2 = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader2 = new SAXReader();

        try {

            Document document2 = saxReader2.read(resourceAsStream2);
            Element rootElement2 = document2.getRootElement();
            List<Element> selectNodes2 = rootElement2.selectNodes("//Host");
            for (int i = 0; i < selectNodes2.size(); i++) {

                //解析server.xml
                Element element =  selectNodes2.get(i);
                String hostName = element.attributeValue("name");
                String appBase = element.attributeValue("appBase");
                Mapper.Host host = mapper.new Host();
                host.setAppBase(appBase);


                //扫描Host对应的目录
                File file = new File(appBase);
                File[] fs = file.listFiles();
                for(int j=0; j<fs.length; j++) {
                    Mapper.Context context = mapper.new Context();
                    String contextName = fs[j].getName();
                    context.setContextName(contextName);

                    //解析context下的Servlet
                    context.setWrapperMap(getWrapperMap(appBase, contextName));
                    host.getContextMap().put(contextName, context);
                }
                mapper.getHostMap().put(hostName, host);
            }
        } catch (DocumentException | MalformedURLException e) {
            e.printStackTrace();
        }

    }

    private Map<String, Mapper.Wrapper> getWrapperMap(String appBase, String contextName) throws MalformedURLException {

        Map<String, Mapper.Wrapper> wrapperMap = new HashMap<>();

        File file = new File(appBase+"/"+contextName);
        URL url = file.toURI().toURL();
        ClassLoader urlClassLoader = new URLClassLoader(new URL[]{url});
        InputStream resourceAsStream = urlClassLoader.getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                Mapper.Wrapper wrapper = mapper.new Wrapper();


                Object o = urlClassLoader.loadClass(servletClass).newInstance();
                wrapper.setHttpServlet((HttpServlet) o);
                wrapperMap.put(urlPattern, wrapper);

            }

        } catch (DocumentException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return wrapperMap;
    }

    public static void main(String[] args) {
        BootStrap bootStrap = new BootStrap();
        try {
            bootStrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
